<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        v-model="form"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
      >
        <template slot-scope="scope" slot="menuLeft">
          <el-popover placement="bottom" width="260">
            <div
              style="text-align: center; margin: 0"
              v-if="batchReviewVisible"
            >
              <el-button size="mini" type="primary" @click="auditO(2)"
                >审批通过</el-button
              >
              <el-button type="primary" size="mini" @click="auditO(3)"
                >审批不通过</el-button
              >
            </div>
            <!-- <el-button type="primary" size="small"  slot="reference">批量审批</el-button> -->
            <el-button
              type="primary"
              size="small"
              v-permission="permissionList.approveBtn"
              slot="reference"
              @click.stop="approve"
              >审批</el-button
            >
          </el-popover>
          <el-button
            type="primary"
            size="small"
            v-permission="permissionList.applyBtn"
            @click.stop="applyTest"
            >申请测试</el-button
          >
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="handleView(scope.row, scope.index)"
            >预览
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            v-if="scope.row.checkStatus == '0'"
            @click="handleEdit(scope.row, scope.index)"
            >编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-check"
            v-permission="permissionList.completeBtn"
            v-if="
              scope.row.testPersonId == userCode &&
              scope.row.checkStatus == '2'
            "
            @click="showTestResult(scope.row)"
            >完善测试信息</el-button
          >
        </template>
        <template slot="listItemIdsForm" slot-scope="scope">
          <el-button
            type="primary"
            :disabled="scope.disabled"
            v-if="boxType != 'view'"
            @click="selectTestItem"
            >选择测试项</el-button
          >
          <!-- <el-checkbox-group v-else v-model="testItems" disabled>
            <div
              class="main-item"
              v-for="item in testItemDic"
              :key="item.value"
            >
              <el-checkbox :label="item.value">{{ item.label }}</el-checkbox>
              <div class="sub-item">
                <el-checkbox
                  v-for="child in item.children"
                  :key="child.value"
                  :label="child.value"
                  >{{ child.label }}
                </el-checkbox>
              </div>
            </div>
          </el-checkbox-group> -->
        </template>
      </avue-crud>
      <open-dialog
        title="选择测试项"
        :DialogVisible.sync="selectTestVisible"
        width="50%"
        center
      >
        <el-checkbox-group v-model="testItems">
          <div class="main-item" v-for="item in testItemDic" :key="item.value">
            <el-checkbox
              :label="item.value"
              @change="itemChange(item, arguments)"
              >{{ item.label }}</el-checkbox
            >
            <div class="sub-item">
              <el-checkbox
                v-for="child in item.children"
                :key="child.value"
                :label="child.value"
                @change="subItemChange(item, child, arguments)"
                >{{ child.label }}
              </el-checkbox>
            </div>
          </div>
        </el-checkbox-group>
        <template slot="footer">
          <el-button
            type="primary"
            size="small"
            @click="selectTestVisible = false"
            >确 认</el-button
          >
          <el-button size="small" @click="selectTestVisible = false"
            >取 消</el-button
          >
        </template>
      </open-dialog>
      <open-dialog title="完善测试信息" :DialogVisible.sync="testResultVisible" :before-close="handleDialogClose">
        <avue-form v-model="testResult" :option="resultFormOption" v-if="testResultVisible"></avue-form>
        <template slot="footer">
          <el-button type="primary" size="small" @click="submitTestResult"
            >确 认</el-button
          >
          <el-button size="small" @click="closeDialog"
            >取 消</el-button
          >
        </template>
      </open-dialog>
      <open-dialog title="预览" :DialogVisible.sync="vieDialogwVisible" :before-close="closeDialogView">
        <div class="header" style="margin-bottom: 20px">基本信息</div>
        <avue-form v-model="viewForm" :option="tableOptionView" v-if="vieDialogwVisible"></avue-form>
        <div class="header" style="margin-bottom: 20px">测试信息</div>
        <avue-form v-model="testResultView" :option="resultFormOptionView" v-if="vieDialogwVisible"></avue-form>
        <div class="bottom-menu">
          <el-button size="small" type="primary" @click="closeDialogView"
            >返 回</el-button
          >
        </div>
      </open-dialog>
    </basic-container>
  </div>
</template>

<script>
import baseCrud from "@/mixins/base-crud";
import {
  getObj,
  putResult,
  getResult,
  testObj,
  approveObj
} from "@/api/subway/swsttickettest";
import { fetchList as fetchTestItems } from "@/api/subway/swsttickettestitem";
import { resultFormOption,tableOptionView,resultFormOptionView,startDate, endDate } from "@/const/crud/subway/swsttickettest";
import store from "@/store";

export default {
  name: "StTicketTest",
  mixins: [baseCrud("subway/swsttickettest")],
  data() {
    return {
      tableOptionView: tableOptionView,
      resultFormOptionView: resultFormOptionView,
      viewForm: {},
      exportName: "车票测试.xlsx",
      selectTestVisible: false,
      vieDialogwVisible: false,
      testItems: [],
      testItemDic: [],
      boxType: "",
      testResult: {},
      testResultView: {},
      testResultVisible: false,
      resultFormOption: resultFormOption,
      batchReviewVisible: false,
      userCode: store.getters.userInfo.userCode,
      searchForm: {
        dates1: [startDate, endDate],
        checkStatus: '0'
      }
    };
  },
  computed: {
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.st_ticket_test_add, false),
        editBtn: this.vaildData(this.permissions.st_ticket_test_update, false),
        delBtn: this.vaildData(this.permissions.st_ticket_test_delete, false),
        applyBtn: this.vaildData(this.permissions.st_ticket_test_apply, false),
        completeBtn: this.vaildData(
          this.permissions.st_ticket_test_complete_result,
          false
        ),
        approveBtn: this.vaildData(
          this.permissions.st_ticket_test_approve,
          false
        )
      };
    }
  },
  created() {
    this.getTestItems();
  },
  methods: {
    handleDialogClose() {
      this.testResultVisible = false;
      for(var i=0;i<=6;i++){
        this.resultFormOption.column[i].display = false;
      }
    },
    closeDialog(){
      this.testResultVisible = false;
      for(var i=0;i<=6;i++){
        this.resultFormOption.column[i].display = false;
      }
    },
    closeDialogView(){
      this.vieDialogwVisible = false;
      for(var i=0;i<=6;i++){
        this.resultFormOptionView.column[i].display = false;
      }
    },
    getTestItems() {
      fetchTestItems({ size: -1 }).then(response => {
        let records = response.data.data.records;
        let dic = [];
        for (let record of records) {
          if (record.parentId == null) {
            let item = {
              label: record.itemLabel,
              value: record.id
            };
            dic.push(item);
            let children = records.filter(r => r.parentId == record.id);
            children = children.map(child => {
              return {
                label: child.itemLabel,
                value: child.id
              };
            });
            item.children = children;
          }
        }
        this.testItemDic = dic;
      });
    },
    beforeRowSave(row, done, loading) {
      row.checkStatus = 0;
      row.listItemIds = this.testItems;
      done();
    },
    beforeRowUpdate(row, index, done, loading) {
      row.listItemIds = this.testItems;
      done();
    },
    selectTestItem() {
      this.selectTestVisible = true;
    },
    beforeOpen(done, type) {
      this.boxType = type;
      if (type != "add") {
        getObj(this.form.id).then(response => {
          this.form = response.data.data;
          this.testItems = this.form.listItemIds;
          done();
        });
      } else {
        this.testItems = [];
        done();
      }
    },
    showTestResult(row) {
      for (var i in this.testResult) {
        this.testResult[i] = "";
      }
      getObj(row.id).then(res => {
        const listItemIds = res.data.data.listItemIds;
        const keys = {
          1: 0, // 票卡外观测试
          11: 1, // 票卡读写高度测试
          25: 2, // 票卡ES编码测试
          15: 3, // 票卡各类查询测试
          30: 4, // 票卡走票性能测试
          22: 5, // 票卡补票性能测试
          33: 6 // 票卡发售测试
        };
        listItemIds.forEach(item =>{
          Object.keys(keys).forEach(key => {
            if (item==key) {
              this.resultFormOption.column[keys[item]].display = true;
            }
          })
        });
        getResult(row.id).then(response => {
          if (response.data.data) {
            this.testResult = response.data.data;
          } else {
            this.testResult = {
              refTestId: row.id,
              testPersonCode: this.$store.getters.userInfo.userCode
            };
          }
          this.testResultVisible = true;
        });
      });
    },
    submitTestResult() {
      putResult(this.testResult).then(response => {
        this.$message.success("完善成功");
        this.closeDialog();
        this.getList(this.page);
      });
    },
    itemChange(item, args) {
      if (args[0]) {
        for (let c of item.children) {
          let index = this.testItems.indexOf(c.value);
          if (index == -1) {
            this.testItems.push(c.value);
          }
        }
      } else {
        for (let c of item.children) {
          let index = this.testItems.indexOf(c.value);
          if (index != -1) {
            this.testItems.splice(index, 1);
          }
        }
      }
    },
    applyTest() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.info("请选择要申请的记录");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.checkStatus !== "0" && table.checkStatus !== "3") {
          this.$message.info("只能申请审核不通过或未提交的数据！");
          return;
        }
        ids.push(table.id);
      }
      testObj(ids)
        .then(data => {
          this.$message.success("申请成功!");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    handleEdit(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    handleView(row, index) {
      getObj(row.id).then(res => {
        this.viewForm = res.data.data;
        const listItemIds = res.data.data.listItemIds;
        const keys = {
          1: 0, // 票卡外观测试
          11: 1, // 票卡读写高度测试
          25: 2, // 票卡ES编码测试
          15: 3, // 票卡各类查询测试
          30: 4, // 票卡走票性能测试
          22: 5, // 票卡补票性能测试
          33: 6 // 票卡发售测试
        };
        listItemIds.forEach(item =>{
          Object.keys(keys).forEach(key => {
            if (item==key) {
              this.resultFormOptionView.column[keys[item]].display = true;
            }
          })
        });
        getResult(row.id).then(response => {
          if (response.data.data) {
            this.testResultView = response.data.data;
          } else {
            this.testResultView = {
              refTestId: row.id,
              testPersonCode: this.$store.getters.userInfo.userCode
            };
          }
        });
      });
      this.vieDialogwVisible = true;
    },
    approve() {
      this.batchReviewVisible = true;
      // if (this.$refs.crud.tableSelect.length < 1) {
      //   this.$message.info("请选择要审批的记录");
      //   return false;
      // }else{
      //   this.batchReviewVisible=true;
      // }
      // let ids = [];
      // for(const table of this.$refs.crud.tableSelect){
      //   ids.push(table.id)
      // }
      // approveObj(ids)
      //   .then((data) => {
      //     this.$message.success("审批成功!");
      //     this.getList(this.page);
      //     done()
      //   })
      //   .catch(() => {
      //     loading();
      //   });
    },
    auditO(s) {
      let loadingInstance1 = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        loadingInstance1.close();
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.checkStatus != "1") {
          this.$message.error("请检查勾选项，只能审批未审核的数据。");
          loadingInstance1.close();
          return false;
        }
        table.checkStatus = s;
        ids.push(table);
      }
      approveObj(ids)
        .then(data => {
          loadingInstance1.close();
          this.$message.success("审批成功");
          this.getList(this.page);
          this.batchReviewVisible = false;
        })
        .catch(() => {
          loadingInstance1.close();
        });
    },
    subItemChange(item, child, args) {
      debugger;
      let itemIndex = this.testItems.indexOf(item.value);
      if (args[0]) {
        if (itemIndex == -1) {
          this.testItems.push(item.value);
        }
      } else {
        let select = false;
        for (let c of item.children) {
          let index = this.testItems.indexOf(c.value);
          if (index != -1) {
            select = true;
            break;
          }
        }
        if (!select && itemIndex != -1) {
          this.testItems.splice(itemIndex, 1);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.main-item {
  margin-bottom: 10px;
  .sub-item {
    margin-top: 10px;
    margin-left: 40px;
  }
}
.bottom-menu {
  text-align: center;
}
.header {
  margin: 0 auto;
  width: 99%;
  padding: 5px 10px;
  border: 1px solid #e4e4e4;
  border-bottom: none;
  background-color: #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
